package webchat;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import util.HttpRequest;

/**
 * 音乐搜索插件 音乐来自网易云音乐
 * @author darren
 * @version 2016年7月18日 下午7:28:43
 *
 */
@WebServlet("/music")
public class MusicPluginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public MusicPluginServlet() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		String name = request.getParameter("name");
		PrintWriter out = response.getWriter();
		JSONArray mp3list = new JSONArray();
		JSONArray result = JSON.parseObject(HttpRequest.post("http://music.163.com/api/search/pc").put("s",name).put("offset",0).put("limit",5).put("type",1).send()).getJSONObject("result").getJSONArray("songs");
		for (Object object : result) {
			JSONObject obj = (JSONObject)object;
			mp3list.add(new JSONObject().fluentPut("url", obj.get("mp3Url")).fluentPut("name", obj.get("name")).fluentPut("art", obj.getJSONArray("artists").getJSONObject(0).get("name")));
		}
		out.print(mp3list.toJSONString());
		out.flush();
		out.close();
	}

}
